package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author Administrator
 */
@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    DishFlavorService dishFlavorService;
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dishDto 传输类
     * @return 返回是否成功
     */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        log.info(dishDto.toString());
        dishService.saveWithFlavor(dishDto);
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("新增成功");
    }

    /**
     * 分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<IPage<DishDto>> page(int page, int pageSize, String name) {
        //设置分页属性
        Page<Dish> pageInfo = new Page<>(page, pageSize);
        //创建查询对象
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        //根据name模糊查询,根据价格排序
        queryWrapper.like(name != null, Dish::getName, name)
                .orderByAsc(Dish::getPrice);
        //执行分页查询
        dishService.page(pageInfo, queryWrapper);
        //把page对象转成DishDto对象
        IPage<DishDto> dishDtoPage = pageInfo.convert(dish -> {
            //创建DishDto对象
            DishDto dishDto = new DishDto();
            //把page属性拷贝到DishDto对象里面
            BeanUtils.copyProperties(dish, dishDto);
            //根据dish获取CategoryId用于查询分类
            Category category = categoryService.getById(dish.getCategoryId());
            //如果有这个分类就赋值
            if (category != null) {
                dishDto.setCategoryName(category.getName());
            }
            return dishDto;
        });

        return R.success(dishDtoPage);

    }

    /**
     * 获取菜品和口味
     *
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public R<DishDto> query(@PathVariable Long id) {
        DishDto byIdWithFlavor = dishService.getByIdWithFlavor(id);
        return R.success(byIdWithFlavor);
    }

    /**
     * 修改菜品信息
     *
     * @param dishDto
     * @return
     */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto) {
        dishService.updateWithFlavor(dishDto);
        String key="dish_"+dishDto.getCategoryId()+"_1";
        redisTemplate.delete(key);
        return R.success("修改成功");
    }

    /**
     * 删除菜品信息
     *
     * @param ids
     * @return
     */
    @DeleteMapping
    public R<String> remove(Long[] ids) {
        //TODO:查询删除的菜品是否在套餐里面
        dishService.removeWithFlavor(ids);
        return R.success("删除成功");
    }

    /**
     * 修改菜品状态
     *
     * @param id
     * @param ids
     * @return
     */
    @PostMapping("/status/{id}")
    public R<String> updateState(@PathVariable Integer id, Long[] ids) {
        log.info("成功,num和ids是" + id + ids);
        //TODO 查询停售的菜品是否在套餐里面
        dishService.updateStateWithFlavor(ids, id);
        return R.success("修改成功");
    }

    /**
     * 套餐页面修改请求菜品分类
     *
     * @param dish
     * @return
     */
    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        //动态构造Redis的key
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        //查询
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        //判断是否存在
        if (dishDtoList!=null){
            return R.success(dishDtoList);
        }
        //构造查询条件
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());
        //添加条件，查询状态为1（起售状态）的菜品
        queryWrapper.eq(Dish::getStatus, 1);

        //添加排序条件
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();

            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id
            //根据id查询分类对象
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            //当前菜品的id
            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);
            //SQL:select * from dish_flavor where dish_id = ?
            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);
            return dishDto;
        }).collect(Collectors.toList());
        //保存到Redis
        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }
}
